package com.gopay.common.util;

import java.security.Key;
import java.security.KeyFactory;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

/**
 * RSA加密类
 * 
 * @RSAEncoder.java
 * @author zhanghongbo
 * @2012-4-19 下午05:22:30 www.gopay.com.cn Inc.All rights reserved.
 */
public class RSAEncoderUtil {

	private static Log logger = LogFactory.getLog(RSAEncoderUtil.class);

	private static final String KEY_ALGORITHM = "RSA";
	private static byte[] publicKey;
	private static byte[] privateKey;

	static {
		try {
			publicKey = new BASE64Decoder().decodeBuffer(GetKeyProperties.getValueBykey("public_key_store"));
			privateKey = new BASE64Decoder().decodeBuffer(GetKeyProperties.getValueBykey("private_key_store"));
		} catch (Exception e) {
			logger.error("初始化密钥异常", e);
		}
	}

	/**
	 * 加密<br>
	 * 用公钥加密
	 * 
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static byte[] encryptByPublicKey(byte[] data, byte[] key)
			throws Exception {
		// 对公钥解密
		// byte[] keyBytes = decryptBASE64(key);

		// 取得公钥
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(key);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Key publicKey = keyFactory.generatePublic(x509KeySpec);

		// 对数据加密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);

		return cipher.doFinal(data);
	}
	
	/**
	 * 加密<br>
	 * 用公钥加密
	 * 
	 * @param data
	 * @return
	 * @throws Exception
	 */
	public static String sign(String data) throws Exception {
		byte[] tempdata = encryptByPublicKey(data.getBytes(), publicKey);
		String tempStrDate = (new BASE64Encoder()).encodeBuffer(tempdata);
		return tempStrDate;
	}

	/**
	 * 解密<br>
	 * 用私钥解密
	 * 
	 * @param data
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static byte[] decryptByPrivateKey(byte[] data, byte[] key)
			throws Exception {
		// 对密钥解密
		// byte[] keyBytes = decryptBASE64(key);

		// 取得私钥
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(key);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);

		// 对数据解密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.DECRYPT_MODE, privateKey);

		return cipher.doFinal(data);
	}
	
	/**
	 * 解密<br>
	 * 用私钥解密
	 * 
	 * @param data
	 *            铭文
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public static String decryptByPrivateKey(String sign) throws Exception {
		byte[] decodeBuffer = new BASE64Decoder().decodeBuffer(sign);
		byte[] tempdata = decryptByPrivateKey(decodeBuffer, privateKey);
		return new String(tempdata);
	}
	

	/**
	 * 验证秘文是否与铭文一致
	 * 
	 * @param plainData
	 *            明文
	 * @param ciphData
	 *            秘文
	 * @return
	 */
	public static boolean verify(String plainData, String sign)
			throws Exception {
		boolean flag = false;
		String databyDecrpt = decryptByPrivateKey(sign);
		flag = plainData.equals(databyDecrpt) ? true : false;
		return flag;
	}


	public static void main(String[] args) {
		String s = "wahaha|9.90|刘俱扬||";
		try {
			System.out.println(sign("BOC100000000001368|6228"));
			System.out.println(verify("BOC100000000001368|6228", "VYCIhlEHCeJ3AIlbJPueA2AqE89i0KL64PZAPtCGQKQtWjsrfHkaIWzaLqIzd4A5kAcH+svf/QitqtedsUtGAnBLdTL3g5YSCXJGLxMoLkvRmPy6JSxYnvGkj/4wsMJeGQPQs27jk6e/vM/XODRCCfqZRFHzHruiVIEgeXEgAgc="));
			 String encryptByPublicKey=sign(s);
			 logger.info(encryptByPublicKey);
			 verify(s,"O+U5gWhYNSaPka/9ppdvI1p/2pWiaA0soDnQDygGVzhc3rD0RuarVai6zM+dCG2vxPxnGftLreD00ZsbVXvXfWNBNEqT6GVTKI/8Zbf47KoGXnUA65NTxUeh8vxmQe3KMj1+JoUWjHWGkl7O8ZGrsirqfnXV4mUaGqDH2lxeNZ4=");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
